import 'package:flutter/material.dart';
import 'dart:async';

// 验证码按钮
class VerificationCodeButton extends StatefulWidget {
  final Function(VoidCallback)? onPressed; // 点击回调
  final int countdownSeconds; // 倒计时秒数
  final String initText; // 初始文本
  final String countdownText; // 倒计时文本，{s}会被替换为秒数
  final TextStyle? enabledTextStyle; // 可用时文本样式
  final TextStyle? disabledTextStyle; // 禁用时文本样式
  final Color? backgroundEnabledColor; // 可用时颜色
  final Color? backgroundDisabledColor; // 禁用时颜色
  final bool autoStart; // 点击后是否自动开始倒计时
  final EdgeInsetsGeometry? padding; // 内边距
  final BorderRadius? borderRadius; // 圆角
  final BoxBorder? border; // 边框

  const VerificationCodeButton({
    Key? key,
    required this.onPressed,
    this.countdownSeconds = 60,
    this.initText = '获取验证码',
    this.countdownText = '{s}秒后重试',
    this.enabledTextStyle,
    this.disabledTextStyle,
    this.backgroundDisabledColor,
    this.backgroundEnabledColor,
    this.autoStart = true,
    this.padding,
    this.borderRadius,
    this.border,
  }) : super(key: key);

  @override
  _VerificationCodeButtonState createState() => _VerificationCodeButtonState();
}

class _VerificationCodeButtonState extends State<VerificationCodeButton> {
  late int _seconds; // 当前秒数
  Timer? _timer; // 计时器
  bool _isCounting = false; // 是否正在倒计时

  @override
  void initState() {
    super.initState();
    _seconds = widget.countdownSeconds;
  }

  @override
  void dispose() {
    _timer?.cancel();
    super.dispose();
  }

  // 开始倒计时
  void _startCountdown() {
    if (_isCounting) return;

    setState(() {
      _isCounting = true;
      _seconds = widget.countdownSeconds;
    });

    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      if (_seconds <= 1) {
        _stopCountdown();
        return;
      }
      setState(() {
        _seconds--;
      });
    });
  }

  // 停止倒计时
  void _stopCountdown() {
    _timer?.cancel();
    setState(() {
      _isCounting = false;
      _seconds = widget.countdownSeconds;
    });
  }

  // 重置倒计时
  void reset() {
    _stopCountdown();
  }

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);
    final backgroundEnabledColor =
        widget.backgroundEnabledColor ?? theme.primaryColor;
    final backgroundDisabledColor =
        widget.backgroundDisabledColor ?? theme.disabledColor;
    final enabledTextStyle =
        widget.enabledTextStyle ?? theme.textTheme.bodyMedium;
    final disabledTextStyle =
        widget.disabledTextStyle ?? theme.textTheme.bodyMedium;

    return GestureDetector(
      onTap: () {
        if (!_isCounting) {
          if (widget.onPressed != null) {
            widget.onPressed!(() {
              _startCountdown();
            });
          }
          if (widget.autoStart) {
            _startCountdown();
          }
        }
      },
      child: Container(
        padding: widget.padding ??
            const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
        decoration: BoxDecoration(
          color: _isCounting ? backgroundDisabledColor : backgroundEnabledColor,
          borderRadius: widget.borderRadius ?? BorderRadius.circular(4),
          border: widget.border,
        ),
        child: Center(
          child: Text(
            _isCounting
                ? widget.countdownText.replaceAll('{s}', _seconds.toString())
                : widget.initText,
            style: _isCounting
                ? widget.disabledTextStyle ?? disabledTextStyle
                : widget.enabledTextStyle ?? enabledTextStyle,
          ),
        ),
      ),
    );
  }
}
